(function(Sea, Win, Doc){
	// 基本目录配置
	var pubjs = '/pubjs/source/';
	var path = Win.location.href.split('#').shift();
	var root = path;
	var app, controller, jQuery, util, platform;

	Win.onerror = function(message, source, line, level, error)
	{
		app.mc.send('error/log', {message: error.stack, type: 'front'});
	};

	// 获取并切换模块容器
	var _lastLayoutName = null;
	function getContainer(config){
		if (util.isString(config)){
			config = util.parse(config);
		}
		var c = util.extend({
			scenes: 'main',
			title: false,
			crumbs: false,
			sitelist: true,
			setup_btn: true,
			module: app.config('router/current_module'),
			action: app.config('router/current_action'),
			menu: '',
			tools: false,
			full: false
		}, config);

		var menu = c.menu.split('/');
		platform
			.switchScenes(c.scenes)		// 更新场景
			//.toggleMenu(!c.full)		// 更新左侧菜单显示状态
			//.toggleTools(c.tools)		// 更新右侧工具显示状态
			.setTitle(c.title)			// 更新标题
			//.setCrumbs(c.crumbs)		// 更新面包屑
			.update(menu[0] || c.module, menu[1] || c.action)	// 更新菜单状态

		if (_lastLayoutName){
			var cont = platform.getContainer(_lastLayoutName, 0, 1);
			if (cont){
				cont.hide();
			}
		}
		_lastLayoutName = c.module + '/' + c.action;
		app.core.cast('switchPage', _lastLayoutName);
		return platform.getContainer(_lastLayoutName, c.scenes, null, c.type).show();
	}
	function getPlatformDom(name){
		if (platform){
			return platform.getDOM(name);
		}else {
			return null;
		}
	}
	function gotoSite(site_id, uri){
		Win.location.href = '/sitevs' + '#' + uri;
	}

	// 项目根目录修正
	function ROOT(path){
		if (root && path.charAt(0) != '/'){
			return root + path;
		}
		return path;
	}

	// 框架根目录修正
	function PUBJS(path){
		if (path.charAt(0) != '/'){
			return pubjs + path;
		}
		return path;
	}

	Win.ROOT = ROOT;
	Win.PUBJS = PUBJS;
	Win._T = function(text){ return text; }

	// 返回SeaJS配置信息
	function sea_config(){
		return {
			base: ROOT("admin/project/"),
			alias: {
				// 全局初始配置
				"sys_config":	ROOT("admin/data/config.js"),
				'globalVMConf': ROOT('data/global_VM_config.js'),
				"@sys_labels":  "modules/labels",

				// 基本模块缩写
				"app":			"@core/pub.js",
				"pubjs":		"@core/pub.js",
				"util":			"@core/util.js",
				"@controller":	"@plugins/controller.js",
				"@tpl":			"@plugins/template.js",
				"jquery":		"@libs/jquery/jquery-1.8.3.min.js",
				"dspUtil":		"modules/dspUtil.js",
				"md5":			"@libs/hmac-md5.js",
				"mock":			"@libs/mock.js",
				"kindEditor":	"@libs/kindEditor/kindeditor-min.js",
				"nicescroll":	"@libs/jquery/jquery.nicescroll.js",
				"jqtouch":		"@libs/jquery/jqtouch.js",
				"@mod/fieldEdit": "modules/fieldEdit.js",
				"@base/highGrid": "modules/grid.js"
			},
			paths: {
				// 目录缩写\
				"@core":		PUBJS("core"),
				"@base":		PUBJS("base"),
				"@pub_base":	PUBJS("base"),
				"@libs":		PUBJS("libs"),
				"@plugins":		PUBJS("plugins"),
				"@layout":		PUBJS("layout"),
				"@mod":		    ROOT('admin/project/modules/'),
				"@share":		ROOT('share'),
				"@project":		ROOT("project"),	//引用最外层project
				"modules":		ROOT("project/modules/")	//引用外层project下的modules
			},
			map: [
				[/^.*$/, function(url){
					/* 加入版本号码 */
					if (Win.VERSION){
						url += (url.indexOf('?') == -1 ? '?v=' : '&v=') + Win.VERSION;
					}
					return url;
				}]
			],
			preload:[
				Win.JSON ? "" : "libs/json.js",
				Function.prototype.bind ? "" : "libs/es5-safe.js",
				// 引入pubjs样式库
				PUBJS('resources/css/uikit.min.css'),
				PUBJS('resources/css/icomoon/style.css'),
				PUBJS('resources/css/subcss/subcss.css'),
				PUBJS('resources/css/app.css')
			],
			debug: 0
		};
	}

	// 全局的检查路由是否有权限，并统一做报错等处理。
	function routerValid(right)
	{
		var user = app.getUser();
		if(!user.current)
		{
			app.controller.navigate("login");
			return;
		}

		if(app.checkRight(right))
		{
			return true;
		}

		// 不需要提示喔
		//app.alert(LANG('没有权限'), function() {
		app.controller.navigate("");
		//}, null, null, true);

		return false;
	}

	// 分部初始化函数
	function INIT_PROCESS(){
		var cb = INIT_STEPS[INIT_STAGE++];
		if (cb){
			cb.apply(Win, arguments);
		}
	}
	var INIT_STAGE = 0;
	var INIT_STEPS = [
		// 修正页面路径
		function(){
			if (root.slice(-1) !== '/'){
				root = root.substr(0, root.lastIndexOf('/') + 1);
			}
			var node = Doc.getElementsByTagName('base');
			if (node.length){
				root = node[0].getAttribute('href');
				node[0].setAttribute('href', path);
			}
			//TODO: 暂时把pubjs部署在项目目录下
			pubjs = ROOT('pubjs/source/');
			// SeaJS全局配置
			Sea.config(sea_config());
			// 引入模块, 开始初始化
			Sea.use(['pubjs', 'sys_config', 'jquery', 'util', 'jqtouch'], INIT_PROCESS);
		},

		// 加载pubjs和系统全局配置
		function(pubjs, config, JQUERY, UTIL){
			app = pubjs;
			jQuery = JQUERY;
			util = UTIL;
			app.getContainer = getContainer;
			app.getPlatformDom = getPlatformDom;
			app.go = gotoSite;
			app.specialTimeWarning = specialTimeWarning;
			app.routerValid = routerValid;

			app.init(config);
			app.config('app/isDebug', location.href.indexOf('?debug') > -1);

			// 加载用户及控制器等插件模块
			app.use([
				'@plugins/controller',
				'@plugins/i18n',
				'@plugins/model',
				'@plugins/user',
				'@plugins/alert',
				'@plugins/codecopy',
				'@plugins/drag',
				'@plugins/mvvm',
				'@plugins/storage',
				'@plugins/mc'
			], INIT_PROCESS);
		},
		// 检测登陆
		function(CONTROLLER){
			controller = CONTROLLER;
			//二级菜单路由操作
			controller.setRouter([
					/^[^#]+#(spot\/(?:[^\/?]+)?)(?:\/([^\/?]+))?(?:\/([^?]+))?(?:\?(.+))?$/,
					/^[^#]+#(ptc\/(?:[^\/?]+)?)(?:\/([^\/?]+))?(?:\/([^?]+))?(?:\?(.+))?$/,
					/^[^#]+#(creative\/(?:[^\/?]+)?)(?:\/([^\/?]+))?(?:\/([^?]+))?(?:\?(.+))?$/,
					/^[^#]+#(adexchange\/(?:[^\/?]+)?)(?:\/([^\/?]+))?(?:\/([^?]+))?(?:\?(.+))?$/,
					/^[^#]+#(exchange\/(?:[^\/?]+)?)(?:\/([^\/?]+))?(?:\/([^?]+))?(?:\?(.+))?$/
				],
				true
			);

			app.mc.onReconnect(function()
			{
				app.mc.send('/login', {'host': Win.location.host}, function(err, data)
				{
					if(!err && data && data.state) {
						if(data && data.state){
							app.setUser(data.userInfo);
						}
						return;
					}

					app.setUser({right: []});
					app.core.cast('sysUserLogout');
					app.controller.navigate('login');
				});
			});
			// 发送登陆请求
			app.mc.send('/login', {'host': Win.location.host}, INIT_PROCESS);
			/*
			 后端登出用户
			 */
			app.mc.on('/logout',function(err,data){
				if (err){
					if (err.message){
						app.alert(err.message);
					}
					app.error(err);
					// 退出失败, 返回上一步地址
					app.controller.navigate(-1);
				}else {
					// 退出登录成功, 跳转到登陆接口
					var last_user = app.getUser();
					var isAdmin = last_user.current && last_user.current.isAdmin;
					app.core.cast('sysUserLogout', last_user);
					app.setUser(null);
					platform.setTitle(app.config('login_title'));
					window.top.pubjs.controller.navigate(app.config('site_base'));
					if(isAdmin){
						Win.top.location.replace(Win.location.href.replace("/admin.html", ""));
					}else {
						Win.location.reload();
					}
				}
			});

			/*
			  监听后台要求的alert message.
			 */
			app.mc.on('map/notice', function(err, data) {
				app.alert(err ? err.message : data.message)
			});
			app.mc.on('category/notice', function(err, data) {
				app.alert(err ? err.message : data.message)
			});
		},
		// 系统模块初始化完成, 创建全局框架
		function(err, data){
			if(err) {
				app.alert(err.message);
				return false;
			}
			if(data && data.state){
				app.setUser(data.userInfo);
			}

			// 记录登陆地址
			app.config('loginUrl', data.loginUrl);
			app.config('logoutUrl', data.logoutUrl);
			app.core.createAsync(
				'SYS_PLATFORM',
				'@layout/v1/platform.base',
				app.config('PLATFORM'),
				INIT_PROCESS
			);
		},
		// 配置完成, 启动应用
		function(PLATFORM){
			app.platform = platform = PLATFORM;
			app.DEFAULT_POPUP_CONTAINER = platform.getDOM('popup');
			app.showSubgrid = platform.popGridPush.bind(platform);
			app.setSubgridParam = platform.setSubGridParam.bind(platform);

			app.showPop = platform.openPop.bind(platform);

			if(app.isLogin())
			{
				var cb = app.config('loginCb');
				if(cb && util.isFunc(cb)) {
					cb(app, function() {
						app.core.cast('sysUserLogin');
						INIT_PROCESS();
					})
				}
			}
			else {
				INIT_PROCESS();
			}
		},
		function() {
			// 移除初始加载界面
			jQuery('body').removeClass('appLoading');
			jQuery('.loadingBoxCircle').remove();
			jQuery('.loadingBox, noscript').remove();
			// 启动路由
			controller.start();
			app.log('PubJS App BOOTED!!');

		}
	];

	// 初始化应用对象
	INIT_PROCESS();

	// 如果用户在0-5点登录后台，弹出强制提醒窗口；
	// 服务器搬迁影响提示
	function specialTimeWarning(){
		// 凌晨0-5点
		if(util.date('H') < 5){
			// 前一天
			var day = util.date('Y-m-d',-24*60*60);
			app.alert('系统正在对'+day+'的数据进行处理中，有包含'+day+'的数据可能存在不完整情况，建议在6点以后进行数据查看。');
		}
	}

})(seajs, window, document);
